﻿using System;
using System.Collections.Generic;
using System.Text;

namespace WFL.Office.Excel
{
    public abstract class DisposableSite : Disposable
    {
        private IList<IDisposable> _chains;

        public DisposableSite()
        {
            _chains = new List<IDisposable>();
        }

        protected void Trace(IDisposable item)
        {
            if (!_chains.Contains(item))
            {
                if (item is Disposable)
                {
                    ((Disposable)item).Disposed += new EventHandler(Item_Disposed);
                }
                _chains.Add(item);
            }
        }

        private void Item_Disposed(object sender, EventArgs e)
        {
            _chains.Remove(sender as IDisposable);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (IDisposable item in _chains)
                {
                    if (item is Disposable)
                    {
                        ((Disposable)item).Disposed -= new EventHandler(Item_Disposed);
                    }
                    item.Dispose();
                }
                _chains.Clear();
            }
        }
    }
}
